from spargameproject.decorators import csrf_www_transaction
from spargameproject.spargame.models import Game, GamePlayer

@csrf_www_transaction(ajax=True, check_auth=True)
def getGameState(req, player=None):
  game_id = req.POST.get('game_id')
  game = Game.objects.get(id=game_id)

  card_to_beat = game.getMetadata('card_to_beat')
  card_to_beat_str = None if not card_to_beat else card_to_beat.fileFormat()

  return {'turn_player': game.getMetadata('turn_player'),
                     'lead_player': game.getMetadata('lead_player'),
                     'dealer': game.getMetadata('dealer'),
                     'lost_players': game.getMetadata('lost_players'),
                     'in_progress': game.getMetadata('in_progress'),
                     'wins': game.getMetadata('wins'),
                     'winner': game.getMetadata('winner'),
                     'scores': game.getMetadata('scores'),
                     'lost_players': game.getMetadata('lost_players'),
                     'card_to_beat': card_to_beat_str,
                     'game_ready': game.getMetadata('ready'),
                     'player_ready': GamePlayer.objects.get(game=game, player=player).getMetadata('ready'),
                     'hand': getHand(game, player),
                     'dries': getDries(game, player)}

def getHand(game, player):
  game_player = game.gameplayer_set.get(player=player)
  return [card.fileFormat() if card else None for card in game_player.getMetadata('cards_left')] or []

def getDries(game, player):
  game_player = game.gameplayer_set.get(player=player)
  dry_indeces = game_player.getMetadata('dry_card_indeces')
  dry_cards = []
  hands = game_player.getMetadata('hand')
  hand = hands[game.getMetadata('session')] if hands else []
  for i, card in enumerate(hand):
    if i in dry_indeces and card:
      dry_cards.append(card.fileFormat())
  return dry_cards
